import Icon from '@/components/Icon';
import { useAppSelector } from '@/store';
import {
  addMyChannelListActionCreator,
  changeMyChannelListActionCreator,
  deleteChannelActionCreator,
  getChannelActionCreator,
  myChannelListActionCreator,
} from '@/store/action/channel';
import { Popup, Tabs } from 'antd-mobile';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import lodash from 'lodash';
import { Channel } from '@/store/reducer/channel';
import history from '@/utils/history';

export function Channels() {
  const dispatch = useDispatch();
  // 从redux中获取首页频道数据
  const { list } = useAppSelector((state) => state.channel);
  // console.log(9, list);

  // 从redux中获取我的频道数据
  const { userChannels } = useAppSelector((state) => state.channel);
  // console.log(20, userChannels);

  // 获取高亮id
  const { activeId } = useAppSelector((state) => state.channel);
  // console.log(29, activeId);

  // 显示弹框控制
  const [showChannel, setShowChannel] = useState(false);

  // 点击编辑显示编辑或者完成符号
  const [edit, setEdit] = useState(false);

  // 计算剩余频道列表(第一种方法)
  // const leftList = list.filter((item) => {
  //   const obj = userChannels.find((item1) => item1.id === item.id);
  //   return obj ? false : item;
  // });
  // console.log(31, leftList);

  // 使用lodash计算剩余频道（第二种方法）
  const leftList = lodash.differenceBy(list, userChannels, 'id');
  // console.log(31, leftList);

  // 点击添加频道
  const handleAddChannel = async (item: Channel) => {
    await dispatch(addMyChannelListActionCreator(item));
  };

  // 点击我的频道里面的数据，有高亮效果，并且跳转
  const handleChange = (id: number) => {
    dispatch(changeMyChannelListActionCreator(id));
    // 跳转对应页面
  };
  useEffect(() => {
    // 获取首页的频道数据
    dispatch(getChannelActionCreator());
    // 获取用户自己的频道数据
    dispatch(myChannelListActionCreator());
  }, [dispatch]);
  return (
    <div>
      {/* 顶部频道 tabs */}
      <div className={styles.channelTabs}>
        <Tabs
          className="tabs"
          activeKey={String(activeId)}
          onChange={(key: string) => handleChange(Number(key))}
        >
          {/* 💥踩坑：Tabs.TabPane 在 v5.0.0-beta.22 版本改名称为 Tabs.Tab */}
          {/* https://github.com/ant-design/ant-design-mobile/issues/4409 */}
          {/* 以前写法：<Tabs.TabPane title='水果' key='fruits' /> */}
          {/* 新版写法：<Tabs.Tab title='水果' key='fruits' /> */}
          {userChannels.map((item) => (
            <Tabs.Tab title={item.name} key={item.id} />
          ))}
        </Tabs>
        <div className="right">
          <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
          <Icon type="iconbtn_channel" onClick={() => setShowChannel(true)} />
        </div>
      </div>
      {/* 编辑频道弹出层 */}
      <Popup
        visible={showChannel}
        position="left"
        bodyClassName={styles.channelPopup}
      >
        {/* 顶部栏：带关闭按钮 */}
        <div className="channel-header">
          <Icon
            type="iconbtn_channel_close"
            onClick={() => {
              setShowChannel(false);
              setEdit(false);
            }}
          />
        </div>

        {/* 频道列表 */}
        <div className="channel-content">
          {/* 当前已选择的频道列表 */}
          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">我的频道</span>
              <span className="channel-item-title-extra">点击进入频道</span>
              <span
                className="channel-item-edit"
                onClick={() => setEdit(!edit)}
              >
                {edit ? '完成' : '编辑'}
              </span>
            </div>
            <div className="channel-list">
              {/* 用户频道列表 list */}
              {userChannels.map((item) => (
                <span
                  key={item.id}
                  // className="channel-list-item"
                  className={classNames(
                    'channel-list-item',
                    item.id === activeId ? 'actived' : ''
                  )}
                  onClick={() => handleChange(item.id)}
                >
                  {item.name}
                  {edit && (
                    <Icon
                      type="iconbtn_tag_close"
                      onClick={(
                        e: React.MouseEvent<HTMLOrSVGElement, MouseEvent>
                      ) => {
                        e.stopPropagation();
                        dispatch(deleteChannelActionCreator(item.id));
                      }}
                    />
                  )}
                </span>
              ))}
            </div>
          </div>

          {/* 推荐的频道列表 */}
          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">频道推荐</span>
              <span className="channel-item-title-extra">点击添加频道</span>
            </div>
            <div className="channel-list">
              {/* 剩下的频道 leftList */}
              {leftList.map((item) => (
                <span
                  key={item.id}
                  className="channel-list-item"
                  onClick={() => handleAddChannel(item)}
                >
                  + {item.name}
                </span>
              ))}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  );
}
